package com.pic.mgt.cli;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

public abstract class CommandLineArgParser {
	private Options options;
	private CommandLine commandLine;
	
	protected CommandLineArgParser() {
		options = new Options();
		
		// 新增共同參數
		addCommonOptions();
		
		// 新增參數
		addOptions(this.options);
	}
	
	private void addCommonOptions() {
		// - help 參數
		this.options.addOption("help", false, "display this help and exit.");
	}
	
	/**
	 * 將要新增的參數寫於本方法中。
	 * @param options
	 */
	protected abstract void addOptions(Options options);
	
	public void parse(String[] args) throws ParseException {
		try {
			CommandLineParser parser = new PosixParser();
			commandLine = parser.parse(this.options, args);
			
			handleCommonOptions();
		} catch (ParseException e) {
			outputNoMatchedOptionsMessage();
			throw e;
		}
	}
	
	public boolean hasArg(String argName) {
		return commandLine.hasOption(argName);
	}
	
	public String getArgValue(String argName) {
		return commandLine.getOptionValue(argName);
	}
	
	public void outputNoMatchedOptionsMessage() {
		System.out.println("invalid options.");
		System.out.println("Try `-help' for more information.");
	}
	
	private void handleCommonOptions() {
		if (commandLine.hasOption("help")) {
			handleHelpOption();
		}
	}
	
	// -help 參數的處理動作
	private void handleHelpOption() {
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp( " ", this.options, true);
		System.exit(0);
	}
}
